package com.braveo.dict;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class ExplanationContentBuilder {
	public static final Pattern CLICK_AREA_PATTERN_01 = Pattern.compile("\\[([^\\[]+)\\]");
	public static final Pattern CLICK_AREA_EXAMPLE_01 = 
			Pattern.compile("^(\\s*\\*\\s*)([a-zA-Z.!,' ]+)");
	
	public static final String JMP_PREFIX = "jmp:";
	public static final String SAY_PREFIX = "say:";
	
	private String explanation;
	private String historyText;
	private BraveImageProvider imageProvider;
	private ArrayList<Integer> imageIdList = new ArrayList<Integer>();

	public ExplanationContentBuilder() {

	}
	
	public ExplanationContentBuilder setExplanation(String explanation) {
		this.explanation = explanation;
		return this;
	}
	
	public ExplanationContentBuilder setHistoryText(String historyText) {
		this.historyText = historyText;
		return this;
	}
	
	public ExplanationContentBuilder setImageProvider(BraveImageProvider imageProvider) {
		this.imageProvider = imageProvider;
		return this;
	}

	public ExplanationContentBuilder setImageIdList(List<Integer> imageIdList) {
		this.imageIdList.clear();
		this.imageIdList.addAll(imageIdList);
		return this;
	}
	
	public CharSequence build() {
		StringBuilder extendedExplain = new StringBuilder().append("TRACK: ")
				.append(historyText).append("\n\n").append(explanation);

		StringReader sr = null;
		StringBuilder sb = new StringBuilder();
		sb.append("<!doctype html><html><head><meta http-equiv=\"Content-Type\" " +
				"content=\"text/html;charset=utf-8\"><body>");

		try {
			sr = new StringReader(extendedExplain.toString());
			BufferedReader br = new BufferedReader(sr, 8192);
			String line;
			while ((line = br.readLine()) != null) {
				Matcher exm = CLICK_AREA_EXAMPLE_01.matcher(line);
				Matcher m = CLICK_AREA_PATTERN_01.matcher(line);
				if (exm.matches()) { // example replacement
					line = exm.replaceFirst("$1<a href=\"" + SAY_PREFIX
							+ "$2\">$2</a>");
				} else if (m.find()) {
					line = m.replaceAll("[<a href=\"" + JMP_PREFIX
							+ "$1\">$1</a>]");
				}
				sb.append(line);
				sb.append("<br />\n");
			}
		} catch (IOException ioex) {

		} finally {
			if (sr != null)
				sr.close();
		}
		
		sb.append(getFakeImageData2());
		sb.append("</body></html>");
		return sb;
	}
	
	@SuppressWarnings("unused")
	private CharSequence getFakeImageData() {
		return new StringBuilder().append("<img src=\"" +
				BraveImageProvider.DICT_IMG_PREFIX +
				"12345\"/>");
	}
	

	private CharSequence getFakeImageData2() {
		StringBuilder sb = new StringBuilder();
		for(Integer imageId : imageIdList) {
			sb.append(imageProvider.createPageData(imageId)).append("<br />");
		}
		
		return sb;
	}
	
	
}
